// lib/pages/main_control_page.dart
import 'dart:math' as math;
import 'package:flutter/material.dart';
import 'package:get/get.dart';

import '../controllers/device_manager_controller.dart';
import 'ozone_page.dart';


class MainControlPage extends StatefulWidget {
  const MainControlPage({Key? key}) : super(key: key);

  @override
  State<MainControlPage> createState() => _MainControlPageState();
}

class _MainControlPageState extends State<MainControlPage> {
  final dm = Get.find<DeviceManagerController>();

  @override
  void initState() {
    super.initState();

    // 初次进页面时，主动拉一下状态（真正的解析都在 controller）
    Future.delayed(const Duration(milliseconds: 300), () async {
      await dm.queryAllStatusOnce();
    });
  }

  // 温度百分比，用于表盘（temp 传当前单位下的数值）
  double _calcTempPercent(double temp, bool isCelsius) {
    final maxT = isCelsius ? 65.0 : 149.0;
    final v = (temp / maxT).clamp(0.0, 1.0);
    return v.isNaN ? 0.0 : v;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color(0xFF101014),
      bottomNavigationBar: _buildBottomNav(),
      body: SafeArea(
        child: SingleChildScrollView(
          padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 12),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              _buildTopBar(),
              const SizedBox(height: 12),
              _buildHeaderRow(),
              const SizedBox(height: 24),
              _buildDialRow(),
              const SizedBox(height: 24),
              _buildFunctionGrid(),
              const SizedBox(height: 24),
              _buildPowerRow(),
              const SizedBox(height: 16),
              _buildDebugInfo(),
            ],
          ),
        ),
      ),
    );
  }

  // 顶部：主控制文字 + 在线状态
  Widget _buildTopBar() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        const Text(
          '主控制 · OK',
          style: TextStyle(color: Colors.white70, fontSize: 12),
        ),
        Obx(() {
          final online = dm.connectedId.value.isNotEmpty;
          return Row(
            children: [
              const Icon(Icons.circle, size: 10, color: Colors.greenAccent),
              const SizedBox(width: 4),
              Text(
                online ? '设备在线' : '未连接',
                style: TextStyle(
                  color: online ? Colors.white : Colors.redAccent,
                  fontSize: 12,
                ),
              ),
            ],
          );
        }),
      ],
    );
  }

  // 中上：sauna 标题 + ℃/℉ 切换（现在是“真切换协议”）
  Widget _buildHeaderRow() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        const Text(
          'sauna',
          style: TextStyle(
            color: Colors.white,
            fontSize: 30,
            fontWeight: FontWeight.bold,
            letterSpacing: 2,
          ),
        ),
        Obx(() {
          final isC = dm.isCelsius.value;
          return Container(
            padding: const EdgeInsets.all(4),
            decoration: BoxDecoration(
              color: const Color(0xFF181820),
              borderRadius: BorderRadius.circular(16),
            ),
            child: Row(
              children: [
                _unitChip('°C', isC, onTap: () {
                  if (!dm.isCelsius.value) {
                    // 切到摄氏（协议层面）
                    dm.switchToCelsiusMode();
                  }
                }),
                const SizedBox(width: 4),
                _unitChip('°F', !isC, onTap: () {
                  if (dm.isCelsius.value) {
                    // 切到华氏（协议层面）
                    dm.switchToFahrenheitMode();
                  }
                }),
              ],
            ),
          );
        }),
      ],
    );
  }

  Widget _unitChip(String text, bool active, {VoidCallback? onTap}) {
    return GestureDetector(
      onTap: onTap,
      child: AnimatedContainer(
        duration: const Duration(milliseconds: 200),
        padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 4),
        decoration: BoxDecoration(
          color: active ? Colors.blueAccent : Colors.transparent,
          borderRadius: BorderRadius.circular(12),
        ),
        child: Text(
          text,
          style: TextStyle(
            color: active ? Colors.white : Colors.white70,
            fontSize: 12,
          ),
        ),
      ),
    );
  }

  // 中部：按设计版布局
  Widget _buildDialRow() {
    return Column(
      children: [
        // 第一行：温度表盘居中，占整行
        Center(
          child: _buildTemperatureDial(),
        ),
        const SizedBox(height: 20),
        // 第二行：左边两个滑块叠在一起，右边时间表盘贯穿两行高度
        Row(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // 左侧：滑块区域（上下两个）
            Expanded(
              flex: 3,
              child: Column(
                children: [
                  _buildSliders(),
                ],
              ),
            ),
            const SizedBox(width: 16),
            // 右侧：时间表盘
            Expanded(
              flex: 2,
              child: _buildTimerDial(),
            ),
          ],
        ),
      ],
    );
  }

  Widget _buildTemperatureDial() {
    return Obx(() {
      final rawTempC = dm.currentTemp.value;     // 内部统一是摄氏
      final isC = dm.isCelsius.value;
      final unit = isC ? '°C' : '°F';

      // 显示温度：根据单位转换
      double displayTemp = rawTempC;
      if (!isC) {
        displayTemp = rawTempC * 9.0 / 5.0 + 32.0;
      }

      final tempLabel = displayTemp <= 0
          ? '--'
          : (isC ? displayTemp.toStringAsFixed(1) : displayTemp.toStringAsFixed(0));

      final percent = _calcTempPercent(displayTemp, isC);
      final target = dm.targetTemp.value; // 已经是当前单位下的数值

      return Column(
        children: [
          SizedBox(
            width: 160,
            height: 160,
            child: Stack(
              alignment: Alignment.center,
              children: [
                // 灰色背景环
                CustomPaint(
                  size: const Size(160, 160),
                  painter: _ArcPainter(
                    startAngle: -210,
                    sweepAngle: 240,
                    color: Colors.grey.shade800,
                    strokeWidth: 16,
                  ),
                ),
                // 彩色渐变进度环
                CustomPaint(
                  size: const Size(160, 160),
                  painter: _GradientArcPainter(
                    startAngle: -210,
                    sweepAngle: 240 * percent,
                    strokeWidth: 18,
                    colors: const [
                      Color(0xFF00E5FF), // 青
                      Color(0xFF76FF03), // 绿
                      Color(0xFFFFEB3B), // 黄
                      Color(0xFFFF9800), // 橙
                      Color(0xFFFF5722), // 红
                    ],
                  ),
                ),
                // 中间文本显示
                Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Text(
                      '$tempLabel$unit',
                      style: const TextStyle(
                        color: Colors.white,
                        fontSize: 30,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                    const SizedBox(height: 4),
                    Text(
                      'set ${target.toStringAsFixed(0)}$unit',
                      style: const TextStyle(
                          color: Colors.white60, fontSize: 12),
                    ),
                    const SizedBox(height: 8),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        const Icon(Icons.local_fire_department,
                            size: 16, color: Colors.white60),
                        const SizedBox(width: 4),
                        Text(
                          '${(percent * 100).toStringAsFixed(0)} %',
                          style: const TextStyle(
                              color: Colors.white70, fontSize: 12),
                        ),
                      ],
                    ),
                  ],
                ),
              ],
            ),
          ),
        ],
      );
    });
  }

  // 左下两个滑块：温度 / 时间
  Widget _buildSliders() {
    return Column(
      children: [
        Obx(() {
          final t = dm.targetTemp.value;
          final isC = dm.isCelsius.value;
          final min = isC ? 25.0 : 77.0;
          final max = isC ? 65.0 : 149.0;
          return _buildSliderRow(
            icon: Icons.thermostat,
            label: '目标温度',
            value: t.clamp(min, max),
            min: min,
            max: max,
            onChanged: (v) {
              dm.targetTemp.value = v;
            },
            onChangeEnd: (v) {
              dm.setTargetTemp(v);
            },
            valueText: t.toStringAsFixed(0),
          );
        }),
        const SizedBox(height: 10),
        Obx(() {
          final m = dm.targetTime.value.toDouble();
          return _buildSliderRow(
            icon: Icons.timer,
            label: '时间',
            value: m,
            min: 1,
            max: 60,
            onChanged: (v) {
              dm.targetTime.value = v.round();
            },
            onChangeEnd: (v) {
              dm.setTargetTime(v.round());
            },
            valueText: '${dm.targetTime.value}',
          );
        }),
      ],
    );
  }

  Widget _buildSliderRow({
    required IconData icon,
    required String label,
    required double value,
    required double min,
    required double max,
    required ValueChanged<double> onChanged,
    required ValueChanged<double> onChangeEnd,
    required String valueText,
  }) {
    return SizedBox(
      height: 44,
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          Icon(icon, color: Colors.white70, size: 22),
          const SizedBox(width: 8),
          Expanded(
            child: Center(
              child: SliderTheme(
                data: SliderTheme.of(context).copyWith(
                  trackHeight: 4,
                  activeTrackColor: Colors.blueAccent,
                  inactiveTrackColor: Colors.white24,
                  thumbShape:
                  const RoundSliderThumbShape(enabledThumbRadius: 10),
                  overlayShape:
                  const RoundSliderOverlayShape(overlayRadius: 18),
                ),
                child: Slider(
                  min: min,
                  max: max,
                  value: value.clamp(min, max),
                  onChanged: onChanged,
                  onChangeEnd: onChangeEnd,
                ),
              ),
            ),
          ),
          const SizedBox(width: 4),
          Align(
            alignment: Alignment.center,
            child: Text(
              valueText,
              style: const TextStyle(color: Colors.white70, fontSize: 14),
            ),
          ),
        ],
      ),
    );
  }

  // 右侧时间表盘（缩小 + 带刻度）
  Widget _buildTimerDial() {
    return Obx(() {
      final t = dm.targetTime.value.toDouble();
      final percent = (t / 60).clamp(0.0, 1.0);

      return Column(
        children: [
          const SizedBox(height: 12),
          SizedBox(
            width: 120,
            height: 120,
            child: Stack(
              alignment: Alignment.center,
              children: [
                // 环形刻度
                CustomPaint(
                  size: const Size(130, 130),
                  painter: _TickArcPainter(
                    startAngle: -210,
                    sweepAngle: 240,
                    minorColor: Colors.white24,
                    majorColor: Colors.white60,
                  ),
                ),
                // 灰色背景环
                CustomPaint(
                  size: const Size(130, 130),
                  painter: _ArcPainter(
                    startAngle: -210,
                    sweepAngle: 240,
                    color: Colors.grey.shade900,
                    strokeWidth: 10,
                  ),
                ),
                // 进度环
                CustomPaint(
                  size: const Size(130, 130),
                  painter: _GradientArcPainter(
                    startAngle: -210,
                    sweepAngle: 240 * percent,
                    strokeWidth: 12,
                    colors: const [
                      Color(0xFF80DEEA),
                      Color(0xFF29B6F6),
                    ],
                  ),
                ),
                // 中央显示
                Column(
                  children: [
                    Text(
                      '${dm.targetTime.value}',
                      style: const TextStyle(
                        color: Colors.white,
                        fontSize: 26,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                    const Text(
                      'min set',
                      style:
                      TextStyle(color: Colors.white60, fontSize: 11),
                    ),
                  ],
                ),
              ],
            ),
          ),
        ],
      );
    });
  }

  // 功能按钮网格（略，同你原来的）
  Widget _buildFunctionGrid() {
    return Obx(() {
      final inner = dm.innerLight.value;
      final outer = dm.outerLight.value;
      final color = dm.colorLight.value;
      final ozone = dm.ozone.value;
      final anion = dm.anion.value;
      final red = dm.redLight.value;

      return GridView.count(
        crossAxisCount: 3,
        mainAxisSpacing: 16,
        crossAxisSpacing: 16,
        shrinkWrap: true,
        physics: const NeverScrollableScrollPhysics(),
        children: [
          _featureButton(
            icon: Icons.lightbulb_outline,
            label: '内灯',
            active: inner,
            onTap: () {
              dm.toggleInnerLight();
            },
          ),
          _featureButton(
            icon: Icons.palette_outlined,
            label: '彩灯',
            active: color,
            onTap: () {
              dm.toggleColorLight();
            },
          ),
          // _featureButton(
          //   icon: Icons.music_note,
          //   label: '音乐',
          //   active: false,
          //   onTap: () {
          //     Get.snackbar('提示', '音乐功能暂未通过 BLE 控制',
          //         snackPosition: SnackPosition.BOTTOM);
          //   },
          // ),


          _featureButton(
            icon: Icons.music_note,
            label: '音乐',
            active: false,   // 如之后根据状态可改成 dm.musicPlaying.value
            onTap: () {
              Get.toNamed('/music');
            },
          ),


          _featureButton(
            icon: Icons.wb_sunny_outlined,
            label: '外灯/氛围灯',
            active: outer,
            onTap: () {
              dm.toggleOuterLight();
            },
          ),

          _featureButton(
            icon: Icons.bubble_chart_outlined,
            label: '臭氧',
            active: ozone,
            onTap: () {
              Get.to(() => const OzonePage());
            },
          ),

        _featureButton(
        icon: Icons.blur_on,
        label: '负离子',
        active: dm.anion.value,
        onTap: () => Get.toNamed('/anion'),
        ),

          _featureButton(
            icon: Icons.bar_chart,
            label: '功率比',
            active: false,
            onTap: () {
              Get.snackbar('提示', '功率比设置可在后续扩展为 3 档',
                  snackPosition: SnackPosition.BOTTOM);
            },
          ),
          _featureButton(
            icon: Icons.wb_incandescent_outlined,
            label: '红灯',
            active: red,
            onTap: () {
              dm.toggleRedLight();
            },
          ),
          _featureButton(
            icon: Icons.favorite_border,
            label: '心率',
            active: false,
            onTap: () async {
              await dm.queryHeartRate();
              Get.snackbar('心率', '已发送获取心率命令（0x11）',
                  snackPosition: SnackPosition.BOTTOM);
            },
          ),
        ],
      );
    });
  }

  Widget _featureButton({
    required IconData icon,
    required String label,
    required bool active,
    required VoidCallback onTap,
  }) {
    return GestureDetector(
      onTap: onTap,
      child: AnimatedContainer(
        duration: const Duration(milliseconds: 180),
        decoration: BoxDecoration(
          color: const Color(0xFF181820),
          borderRadius: BorderRadius.circular(18),
          boxShadow: [
            BoxShadow(
              color:
              active ? Colors.blueAccent.withOpacity(0.4) : Colors.black54,
              offset: const Offset(3, 3),
              blurRadius: 8,
            ),
          ],
          border: Border.all(
            color: active ? Colors.blueAccent : Colors.transparent,
            width: 1,
          ),
        ),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(icon,
                color: active ? Colors.blueAccent : Colors.white70, size: 26),
            const SizedBox(height: 6),
            Text(
              label,
              style: TextStyle(
                color: active ? Colors.blueAccent : Colors.white70,
                fontSize: 13,
              ),
            ),
          ],
        ),
      ),
    );
  }

  // 底部：电源按钮
  Widget _buildPowerRow() {
    return Obx(() {
      final on = dm.powerOn.value;

      return Row(
        mainAxisAlignment: MainAxisAlignment.spaceAround,
        children: [
          _roundMiniButton(
            icon: Icons.local_fire_department_outlined,
            label: '卡路里',
            onTap: () {
              Get.snackbar('提示', '卡路里统计将放在“健康”页',
                  snackPosition: SnackPosition.BOTTOM);
            },
          ),
          GestureDetector(
            onTap: () {
              dm.togglePower();
            },
            child: AnimatedContainer(
              duration: const Duration(milliseconds: 200),
              width: 86,
              height: 86,
              decoration: BoxDecoration(
                shape: BoxShape.circle,
                color: on ? Colors.blueAccent : Colors.grey.shade700,
                boxShadow: [
                  BoxShadow(
                    color: Colors.black.withOpacity(0.6),
                    offset: const Offset(4, 4),
                    blurRadius: 10,
                  ),
                ],
              ),
              child: const Icon(Icons.power_settings_new,
                  color: Colors.white, size: 40),
            ),
          ),
          _roundMiniButton(
            icon: Icons.favorite,
            label: '心率',
            onTap: () async {
              await dm.queryHeartRate();
            },
          ),
        ],
      );
    });
  }

  Widget _roundMiniButton({
    required IconData icon,
    required String label,
    required VoidCallback onTap,
  }) {
    return Column(
      children: [
        GestureDetector(
          onTap: onTap,
          child: Container(
            width: 52,
            height: 52,
            decoration: BoxDecoration(
              shape: BoxShape.circle,
              color: const Color(0xFF181820),
              boxShadow: [
                BoxShadow(
                  color: Colors.black.withOpacity(0.6),
                  offset: const Offset(3, 3),
                  blurRadius: 8,
                ),
              ],
            ),
            child: Icon(icon, color: Colors.white70, size: 26),
          ),
        ),
        const SizedBox(height: 6),
        Text(
          label,
          style: const TextStyle(color: Colors.white60, fontSize: 12),
        ),
      ],
    );
  }

  // 底部导航栏
  Widget _buildBottomNav() {
    return BottomNavigationBar(
      backgroundColor: const Color(0xFF15151B),
      selectedItemColor: Colors.orangeAccent,
      unselectedItemColor: Colors.white54,
      currentIndex: 0,
      onTap: (i) {
        if (i == 2) {
          Get.toNamed('/wifi_config');
        }
      },
      items: const [
        BottomNavigationBarItem(icon: Icon(Icons.home), label: "首页"),
        BottomNavigationBarItem(icon: Icon(Icons.eco_outlined), label: "健康"),
        BottomNavigationBarItem(icon: Icon(Icons.settings), label: "设置"),
      ],
    );
  }

  // 调试信息
  Widget _buildDebugInfo() {
    return Obx(() {
      return Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const Text(
            '最近回包：',
            style: TextStyle(color: Colors.white60, fontSize: 12),
          ),
          const SizedBox(height: 4),
          Text(
            dm.lastPacket.value,
            style: const TextStyle(color: Colors.white38, fontSize: 11),
          ),
        ],
      );
    });
  }
}

// ======================================================
// 🎨 自定义圆弧画笔（原样 + 刻度画笔）
// ======================================================

class _ArcPainter extends CustomPainter {
  final double startAngle; // 角度制
  final double sweepAngle; // 角度制
  final Color color;
  final double strokeWidth;

  _ArcPainter({
    required this.startAngle,
    required this.sweepAngle,
    required this.color,
    required this.strokeWidth,
  });

  @override
  void paint(Canvas canvas, Size size) {
    final rect = Offset.zero & size;
    final paint = Paint()
      ..color = color
      ..style = PaintingStyle.stroke
      ..strokeCap = StrokeCap.round
      ..strokeWidth = strokeWidth;

    final startRad = startAngle * math.pi / 180;
    final sweepRad = sweepAngle * math.pi / 180;

    canvas.drawArc(
        rect.deflate(strokeWidth / 2), startRad, sweepRad, false, paint);
  }

  @override
  bool shouldRepaint(_ArcPainter oldDelegate) =>
      oldDelegate.color != color ||
          oldDelegate.strokeWidth != strokeWidth ||
          oldDelegate.startAngle != startAngle ||
          oldDelegate.sweepAngle != sweepAngle;
}

class _GradientArcPainter extends CustomPainter {
  final double startAngle;
  final double sweepAngle;
  final double strokeWidth;
  final List<Color> colors;

  _GradientArcPainter({
    required this.startAngle,
    required this.sweepAngle,
    required this.strokeWidth,
    required this.colors,
  });

  @override
  void paint(Canvas canvas, Size size) {
    if (sweepAngle <= 0) return;

    final rect = Offset.zero & size;
    final startRad = startAngle * math.pi / 180;
    final sweepRad = sweepAngle * math.pi / 180;

    final paint = Paint()
      ..style = PaintingStyle.stroke
      ..strokeWidth = strokeWidth
      ..strokeCap = StrokeCap.round
      ..shader = SweepGradient(
        colors: colors,
        startAngle: startRad,
        endAngle: startRad + sweepRad,
      ).createShader(rect.deflate(strokeWidth / 2));

    canvas.drawArc(
        rect.deflate(strokeWidth / 2), startRad, sweepRad, false, paint);
  }

  @override
  bool shouldRepaint(_GradientArcPainter oldDelegate) =>
      oldDelegate.sweepAngle != sweepAngle ||
          oldDelegate.strokeWidth != strokeWidth ||
          oldDelegate.colors != colors;
}

// 表盘刻度 Painter
class _TickArcPainter extends CustomPainter {
  final int total; // 总刻度数量，60
  final int major; // 大刻度周期，5
  final double startAngle; // 起始角度（角度制）
  final double sweepAngle; // 总弧长（角度制）
  final Color minorColor;
  final Color majorColor;

  _TickArcPainter({
    this.total = 60,
    this.major = 5,
    required this.startAngle,
    required this.sweepAngle,
    required this.minorColor,
    required this.majorColor,
  });

  @override
  void paint(Canvas canvas, Size size) {
    final center = size.center(Offset.zero);
    final radius = size.width / 2;

    final minorPaint = Paint()
      ..color = minorColor
      ..strokeWidth = 2
      ..strokeCap = StrokeCap.round;

    final majorPaint = Paint()
      ..color = majorColor
      ..strokeWidth = 3
      ..strokeCap = StrokeCap.round;

    final double start = startAngle * math.pi / 180;
    final double sweep = sweepAngle * math.pi / 180;

    for (int i = 0; i <= total; i++) {
      final double ang = start + sweep * (i / total);

      final double inner = radius - 10;
      final double outer = (i % major == 0) ? radius : radius - 6;

      final p1 = Offset(
        center.dx + inner * math.cos(ang),
        center.dy + inner * math.sin(ang),
      );
      final p2 = Offset(
        center.dx + outer * math.cos(ang),
        center.dy + outer * math.sin(ang),
      );

      canvas.drawLine(
        p1,
        p2,
        (i % major == 0) ? majorPaint : minorPaint,
      );
    }
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) => false;
}
